package com.lineage.server.timecontroller.skill;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldDragonKnight;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Skill_Awake_Timer extends TimerTask {
  private static final Log _log = LogFactory.getLog(Skill_Awake_Timer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
  
  public void run() {
    try {
      Collection<L1PcInstance> allPc = WorldDragonKnight.get().all();
      if (allPc.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = allPc.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        if (tgpc.isDead())
          continue; 
        if (!tgpc.isMpReductionActiveByAwake())
          continue; 
        int time = tgpc.get_awakeMprTime();
        if (--time <= 0) {
          decreaseMp(tgpc);
          tgpc.set_awakeMprTime(4);
        } else {
          tgpc.set_awakeMprTime(time);
        } 
        Thread.sleep(1L);
      } 
    } catch (Exception e) {
      _log.error("龙骑士觉醒技能MP自然减少处理异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      Skill_Awake_Timer awake_Timer = new Skill_Awake_Timer();
      awake_Timer.start();
    } 
  }
  
  private static void decreaseMp(L1PcInstance tgpc) {
    try {
      int newMp = Math.max(tgpc.getCurrentMp() - 8, 0);
      tgpc.setCurrentMp(newMp);
    } catch (Throwable e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
